package org.liaohailong.library.widget.common;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Outline;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.view.View;
import android.view.ViewOutlineProvider;

import androidx.annotation.NonNull;

/**
 * Author: liaohailong
 * Date: 2022/8/28
 * Time: 9:36
 * Description: 裁剪圆角功能代理
 **/
class CommonCropDelegate {


    private int radius = 0;

    private float strokeWidth;
    private int strokeColor;


    private final RectF strokeRectF = new RectF();
    private final Paint strokePaint = new Paint();

    {
        strokePaint.setAntiAlias(true);
        strokePaint.setStyle(Paint.Style.STROKE);
        strokePaint.setColor(Color.TRANSPARENT);
    }

    @NonNull
    private final View view;

    public CommonCropDelegate(@NonNull View view) {
        this.view = view;
    }

    void post(@NonNull Runnable runnable) {
        view.post(runnable);
    }

    int getMeasuredWidth() {
        return view.getMeasuredWidth();
    }

    int getMeasuredHeight() {
        return view.getMeasuredHeight();
    }

    void invalidate() {
        view.invalidate();
    }

    void setup(int radius, float strokeWidth, int strokeColor) {

        this.radius = radius;
        this.strokeWidth = strokeWidth;
        this.strokeColor = strokeColor;
        strokePaint.setStrokeWidth(strokeWidth);
        strokePaint.setColor(strokeColor);
    }


    void setRadius(int radius) {
        this.radius = radius;
        post(() -> {
            prepareShape(getMeasuredWidth(), getMeasuredHeight());
            invalidate();
        });
    }

    void setStrokeColor(int strokeColor) {
        this.strokeColor = strokeColor;
        this.strokePaint.setColor(strokeColor);
        post(() -> {
            prepareShape(getMeasuredWidth(), getMeasuredHeight());
            invalidate();
        });
    }

    void setStrokeWidth(float strokeWidth) {
        this.strokeWidth = strokeWidth;
        this.strokePaint.setStrokeWidth(strokeWidth);
        post(() -> {
            prepareShape(getMeasuredWidth(), getMeasuredHeight());
            invalidate();
        });
    }

    void prepareShape(int w, int h) {
        // 使用outline的方式裁剪view
        view.setOutlineProvider(new ViewOutlineProvider() {
            @Override
            public void getOutline(View view, Outline outline) {
                outline.setRoundRect(0, 0, w, h, radius);
            }
        });
        view.setClipToOutline(true);
        // 处理边线，内收缩
        strokeRectF.set(0, 0, w, h);
        if (strokeWidth > 0) {
            strokeRectF.inset(strokeWidth / 2, strokeWidth / 2);
        }
    }

    public void drawStroke(@NonNull Canvas canvas) {
        if (strokeWidth > 0)
            canvas.drawRoundRect(strokeRectF, radius, radius, strokePaint);
    }
}
